// app/model/customer_model.js
'use strict';

module.exports = app => {
  const { STRING, INTEGER, TEXT, TINYINT, DATE } = app.Sequelize;

  const Customer = app.model.define('customer', {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    organizationId: {
      type: INTEGER,
      allowNull: false,
      field: 'organization_id',
      comment: '组织ID'
    },
    name: {
      type: STRING(200),
      allowNull: false,
      comment: '客户名称'
    },
    code: {
      type: STRING(100),
      comment: '客户编码'
    },
    // 删除原来的contactPersons字段，因为我们现在使用关联关系
    status: {
      type: TINYINT,
      defaultValue: 1,
      comment: '状态:1启用,0禁用'
    },
    // 新增的客户价值相关字段
    customerType: {
      type: STRING(50),
      field: 'customer_type',
      comment: '客户类型'
    },
    customerLevel: {
      type: STRING(50),
      field: 'customer_level',
      comment: '客户等级'
    },
    customerSource: {
      type: STRING(100),
      field: 'customer_source',
      comment: '客户来源'
    },
    creditRating: {
      type: STRING(10),
      field: 'credit_rating',
      comment: '信用评级'
    },
    creditScore: {
      type: INTEGER,
      field: 'credit_score',
      comment: '信用分数'
    },
    responsibleSalesman: {
      type: STRING(100),
      field: 'responsible_salesman',
      comment: '负责销售'
    },
    lastOrderDate: {
      type: DATE,
      field: 'last_order_date',
      comment: '最后下单时间'
    },
    createdAt: {
      type: DATE,
      field: 'created_at'
    },
    updatedAt: {
      type: DATE,
      field: 'updated_at'
    }
  }, {
    tableName: 'customers',
    timestamps: true,
    underscored: true
  });

  // 添加关联关系
  Customer.associate = function() {
    // 确保关联的模型存在
    if (app.model.SalesOrderModel) {
      Customer.hasMany(app.model.SalesOrderModel, {
        foreignKey: 'customerId',
        as: 'salesOrders'
      });
    }

    // 客户与组织的关联
    if (app.model.OrganizationModel) {
      Customer.belongsTo(app.model.OrganizationModel, {
        foreignKey: 'organizationId',
        as: 'organization'
      });
    }

    // 客户与联系人的关联（一对多）
    if (app.model.ContactPersonModel) {
      Customer.hasMany(app.model.ContactPersonModel, {
        foreignKey: 'customerId',
        as: 'contacts'
      });
    }
  };

  return Customer;
};